/**
 * 加载资源
 */
class LoadScene extends Scene {


	private static _ins: LoadScene;
	public static get ins(): LoadScene {
		if (!LoadScene._ins) {
			LoadScene._ins = new LoadScene();
		}
		return LoadScene._ins;
	}



	// 资源组
	private _resGroup: string;
	// 要跳转的场境
	private _enterSceneCls: Scene;
	// 进度条最大长度
	private _barMaxWidth: number;
	// main初始y值
	private _initMainY: number;

	// logo
	private grpMain: eui.Label;
	// 资源加载进度条组
	private grpProgress: eui.Group;
	// 资源加载进度条条
	private imgProgress: eui.Image;


	public constructor() {
		super();
		if (LoadScene._ins) {
			throw new Error("LoadScene 使用了单例");
		}
		this.skinName = LoadSceneSkin;
	}



	protected createChildren() {
		this._barMaxWidth = this.grpProgress.width;
		this._initMainY = this.grpMain.verticalCenter;
	}



	/**
	 * 加载完资源组跳转场境
	 * @param	resGroup	资源组
	 * @param	cls			要跳转的场境
	 */
	public load(resGroup: string, cls: Scene) {
		// 跳转到当前场境
		SceneManager.ins.changeScene(LoadScene.ins);

		// 记录必要属性
		this._resGroup = resGroup;
		this._enterSceneCls = cls;
		this.initScene();
	}



	/**
	 * 初始化场境
	 */
	private initScene() {
		this.grpMain.verticalCenter = this._initMainY;
		this.grpMain.scaleX = 1;
		this.grpMain.scaleY = 1;
		this.imgProgress.width = 0;
		this.startLoad()
	}



	/**
	 * 开始加载
	 */
	private startLoad() {
		// 监听下载完成和下载出错
		RES.addEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this);
		RES.addEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, this.onResourceLoadComplete, this);
		// 监听进度
		RES.addEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this);
		RES.loadGroup(this._resGroup);
	}




	/**
	 * 进度
	 */
	private onResourceProgress(e: RES.ResourceEvent) {
		if (e.groupName == this._resGroup) {
			var p = e.itemsLoaded / e.itemsTotal;
			var rate: number = p * this._barMaxWidth;
			egret.Tween.removeTweens(this.imgProgress);
			egret.Tween.get(this.imgProgress)
				.to({ width: rate }, 250, egret.Ease.sineOut);
		}
	}




	/**
	 * 当资源负载完成
	 */
	private onResourceLoadComplete(e: RES.ResourceEvent) {
		if (e.groupName == this._resGroup) {
			egret.Tween.get(this.grpMain)
				.to({ verticalCenter: this._initMainY + 200, scaleX: 0, scaleY: 0 }, 350)
				.call(() => {
					// 跳转
					SceneManager.ins.changeScene(this._enterSceneCls)
				});
		}
	}



}